<template>
  <div>
    <AuthComponent></AuthComponent>
    <div>
      <el-button type="primary" @click="goBlogList">返回到文章列表</el-button>
      <el-button type="primary" @click="openDialog">续写文章</el-button>
      <span style="margin: 20px;">阅读量: {{blog.views}}</span>
    </div>
    <div style="font-size: 30px; position: fixed; right: 200px; top: 500px; background: #42b983; width: 100px; height: 100px; line-height: 50px;text-align: center">
      <div >
        <!--点赞-->
        <i class="el-icon-thumb" @click="clickLikes"></i>
        <span style="margin-left: 5px;">{{blog.likes}}</span>
      </div>
      <div>
        <!--收藏-->
        <i class="el-icon-collection-tag" @click="collectBlog"></i>
      </div>
    </div>
    <!--文章-->
    <div style="margin: 20px 0;">
      <!--头部-->
      <div style="position: relative;">
        <div style="font-size: 40px;padding:20px 10px; margin: 20px 0;color: #409EFF; text-align: center">
          {{blog.title}}
        </div>
        <div  style="font-size: 14px;padding: 0 10px; color: #C0C4CC;position: absolute;right:40px;bottom:-10px;">
        <span>
            <i class="el-icon-user"></i>
            {{blog.creatorName}}
        </span>
          <span>
            <i class="el-icon-time"></i>
            {{ blog.createTime }}
         </span>
        </div>
      </div>
      <!--内容-->
      <div style="line-height: 30px; text-indent: 2em;">
        <div v-html="blog.render" style="margin: 0 auto"></div>
      </div>
    </div>
    <!--评论区-->
    <div>
      <el-divider content-position="center">Come On!!!! Baby!!!</el-divider>
    </div>
    <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="评论" prop="content">
          <el-input type="textarea" v-model="ruleForm.content"></el-input>
        </el-form-item>
        <el-form-item>
          <!--直接对博客评论-->
          <el-button type="primary" @click="save('ruleForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div>
        <el-divider content-position="center">评论展示区</el-divider>
      </div>
      <div style="padding: 0 30px;">
        <div v-for="(item, index) in commentArray" :key="item.id" style="padding: 0 10px;margin: 10px 0;">
          <!--主评论-->
          <div style="font-size: 14px;padding: 10px 10px; color: #C0C4CC; position: relative">
            <span style="margin-right:20px">
               <i class="el-icon-user"></i>
               <span v-if="userInfo && item.creatorId === userInfo.id">
                  我自己
               </span>
               <span v-else>
                 {{ item.creatorName }}:
               </span>
            </span>
            <span style="color: black;margin-right:20px">
                {{ item.content }}
            </span>
            <div style="position:absolute;top:5px;right:30px;">
              <span>
                 <i class="el-icon-time"></i>
                {{ item.createTime }}
              </span>
              <el-button type="primary" @click="setReplyForm(item, null, index)" size="mini" v-if="userInfo && item.creatorId != userInfo.id">回复</el-button>
            </div>
          </div>

          <CommentForm v-if="commentMasterIndex === index">
            <template v-slot:commentForm>
              <el-form :model="replyRuleForm" :rules="rules" ref="replyRuleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="内容" prop="content">
                  <el-input type="textarea" v-model="replyRuleForm.content"></el-input>
                </el-form-item>
                <el-form-item>
                  <!--直接对博客评论-->
                  <el-button type="primary" @click="save('replyRuleForm', 2)">提交</el-button>
                </el-form-item>
              </el-form>
            </template>
          </CommentForm>

          <!--副评论-->
          <div  style="padding: 0 10px; margin: 0 30px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);font-size: 14px;color: #C0C4CC">
            <div v-for="replyItem in item.replyList" :key="replyItem.id" style="margin: 10px 0;position: relative;padding: 10px 0;">
              <span style="margin-right:20px">
                <i class="el-icon-user"></i>
                <span v-if="userInfo && replyItem.creatorId === userInfo.id">
                  我自己
                </span>
               <span v-else>
                  {{ replyItem.creatorName }}
               </span>
               回复
                <span style="color: #67C23A">
                  <i class="el-icon-user"></i>
                  <span v-if="userInfo && replyItem.repliedUserId === userInfo.id">
                    我自己
                  </span>
                 <span v-else>
                    {{ replyItem.repliedUserName }}
                 </span>
                </span>
              </span>
              <span style="color: black">
                {{ replyItem.content }}
              </span>
              <div style="position:absolute;top:5px;right:-10px;">
                 <span >
                   <i class="el-icon-time"></i>
                   {{ replyItem.createTime }}
                 </span>
                <el-button type="primary" @click="setReplyForm(item, replyItem)"  size="mini" v-if="userInfo && replyItem.creatorId != userInfo.id">回复</el-button>
              </div>

              <CommentForm v-if="commentSlaveId === replyItem.id">
                <template v-slot:commentForm>
                  <el-form :model="replyRuleForm" :rules="rules" ref="replyRuleForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="内容" prop="content">
                      <el-input type="textarea" v-model="replyRuleForm.content"></el-input>
                    </el-form-item>
                    <el-form-item>
                      <!--直接对博客评论-->
                      <el-button type="primary" @click="save('replyRuleForm', 2)">提交</el-button>
                    </el-form-item>
                  </el-form>
                </template>
              </CommentForm>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--分页-->
    <div class="block" style="width: 50%; margin: 0 auto;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
      <el-form :model="blog" :rules="rules" ref="blog" label-width="100px" class="demo-ruleForm">
        <el-form-item label="内容" prop="content">
          <span style="color: red">提示： 您续写的内容会打上您的用户名标签</span>
          <mavon-editor v-model="blog.continueArticle" @change="saveContent" ref=md @imgAdd="$imgAdd"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveArticle('blog', 2)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommentForm from "@/components/commen/CommentForm";
import AuthComponent from "@/components/commen/AuthComponent";

export default {
  name: "BlogShow",
  components: {
    CommentForm,
    AuthComponent
  },
  data() {
    return {
      dialogFormVisible: false,
      userInfo: {
        token: null,
        userName: ''
      },
      blog: {
        likes: 0,
        views: 0,
        title: '',
        content: '',
        blogId: '',
        replyId: null,
        replyRootId: null,
        continueArticle: "",
        continueRender: ""
      },
      commentArray: [],
      commentMasterIndex: 10000,
      commentSlaveId: null,
      pageSize: 5,
      currentPage: 0,
      total: 0,
      ruleForm: {
        content: '',
        blogId: '',
        replyId: null,
        replyRootId: null
      },
      replyRuleForm: {
        content: '',
        blogId: '',
        replyId: null,
        replyRootId: null
      },
      rules: {
        content: [
          { required: true, message: '请填写内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 获取到路径上blogId
    let blogId = this.$route.params.blogId
    // 查询博客内容
    this.getBlogDetail(blogId)
    this.userInfo = this.$store.state.userInfo
  },
  methods: {
    collectBlog() {
      let blogCollect = {
        blogId: this.blog.id,
        title: this.blog.title,
        creatorId: this.userInfo.id,
        creatorName: this.userInfo.userName
      }
      this.$http.post("/blog/collection", blogCollect, {headers: {token: this.userInfo.token}}).then(res => {
        res = res.data;
        if (res.code === 0) {
          this.$message({
            message: '收藏成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.message,
            type: 'warning'
          });
        }
      }).catch((error) => {
        console.log(error);
      });
    },
    getBlogDetail(blogId) {
      this.$http.get("/blog/detail/" + blogId).then(res => {
        res = res.data
        if (res.code === 0) {
          this.blog = res.data;
          this.getCommentArray()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    clickLikes() {
      this.$http.get("/blog/clickLikes/"+this.blog.id).then(res => {
        res = res.data;
        if (res.code === 0) {
          this.$message({
            message: '点赞成功',
            type: 'success'
          });
          this.blog.likes = res.data
        } else {
          this.$message({
            message: '点赞失败',
            type: 'warning'
          });
        }
      }).catch((error) => {
        console.log(error);
      });
    },
    saveArticle(formName, state) {
      if (!this.userInfo) {
        this.$message({
          message: '请您先登录, 登录后就能愉快的发布文章了',
          type: 'warning'
        });
        return;
      }
      if (!this.blog.continueArticle) {
        this.$message({
          message: '请您先保存文章后, 再提交',
          type: 'warning'
        });
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 1.保存 2.发布
          this.blog.publishState = state
          this.blog.content += "\n" + this.blog.continueArticle
          this.blog.render =this.blog.render +  `<div><div data-v-6d56066f="" class="el-divider el-divider--horizontal" style=""><div data-v-6d56066f="" class="el-divider__text is-left" style="color: red;font-size: 20px;">续写人： ${this.blog.creatorName}</div></div>${this.blog.continueRender}</div>`
          this.$http.post("/blog/save", this.blog, {headers: {token: this.userInfo.token}}).then(res => {
            res = res.data;
            if (res.code === 0) {
              this.$message({
                message: '保存成功',
                type: 'success'
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: '保存失败',
                type: 'warning'
              });
            }
          }).catch((error) => {
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
        this.blog.continueArticle = "";
        this.blog.continueRender = "";

      });
    },
    saveContent(value, render) {
      this.blog.continueArticle = value;
      this.blog.continueRender = render;
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file){
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append('multipartFile', $file);
      this.$http({
        url: '/oss/upload',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((res) => {
        /**
         * 例如：返回数据为 res = [[pos, url], [pos, url]...]
         * pos 为原图片标志（0）
         * url 为上传后图片的url地址
         */
        console.log(res)
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        $vm.$img2Url(pos, "http://www.baidu.com");
      })
    },
    openDialog() {
       this.dialogFormVisible = true
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getCommentArray()
    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum;
      this.getCommentArray()
    },
    setReplyForm(item, replyItem, index) {
      if (replyItem == null) {
        // 对评论的回复
        this.replyRuleForm.replyId = item.id;
        this.replyRuleForm.blogId = item.blogId;
        this.replyRuleForm.replyRootId = item.id
        this.replyRuleForm.repliedUserName = item.creatorName
        this.replyRuleForm.repliedUserId = item.creatorId
        this.commentMasterIndex = index;
        // 影藏副评论板块
        this.commentSlaveId = null;
      } else {
        // 对评论的评论的回复
        this.replyRuleForm.replyId = replyItem.id;
        this.replyRuleForm.blogId = item.blogId;
        this.replyRuleForm.replyRootId = item.id
        this.replyRuleForm.repliedUserName = replyItem.creatorName
        this.replyRuleForm.repliedUserId = replyItem.creatorId
        this.commentSlaveId = replyItem.id;
        // 隐藏主评论回复板块
        this.commentMasterIndex = 10000;
      }
    },
    goBlogList() {
      let flag = this.$route.params.flag
      if (flag == 1) {
        this.$router.push({path: "/"})
      } else if (flag == 2)  {
        this.$router.push({path: "/blog/person/list"})
      }

    },
    getCommentArray() {
      let currentPage = 0;
      if (this.currentPage <= 0) {
        currentPage = 0;
      } else {
        currentPage = this.currentPage - 1;
      }
      this.$http.get("/comment/detail/"+this.blog.id + "?pageNum="+currentPage+"&pageSize="+this.pageSize).then(res => {
        res = res.data
        if (res.code === 0) {
          res = res.data;
          this.commentArray = res.content
          this.total = res.totalElements;
          this.currentPage = res.number + 1;
        }
      }).catch(err => {
        console.log(err)
      })
    },
    save(formName, state) {
      let userInfo = localStorage.getItem("userInfo");
      if (!userInfo) {
        this.$message({
          message: '请您先登录, 登录后就能愉快的评论了',
          type: 'warning'
        });
        return;
      }
      let ref = null
      if (state) {
        ref = this.$refs[formName][0]
      } else {
        ref = this.$refs[formName]
      }
      ref.validate((valid) => {
        if (valid) {
          this.ruleForm.blogId = this.blog.id
          if (state) {
            // 主评论
            this.ruleForm = JSON.parse(JSON.stringify(this.replyRuleForm));
          }
          this.$http.post("/comment/save", this.ruleForm, {headers: {token: this.userInfo.token}}).then(res => {
            res = res.data;
            if (res.code === 0) {
              // 对评论的评论
              this.currentPage--;
              this.getCommentArray()
              this.$message({
                message: '评论成功',
                type: 'success'
              });
              this.ruleForm = {
                content: '',
                blogId: '',
                replyId: null,
                replyRootId: null
              };
              this.replyRuleForm = {
                content: '',
                blogId: '',
                replyId: null,
                replyRootId: null
              };
              // 影藏副评论板块
              this.commentSlaveId = null;
              // 隐藏主评论回复板块
              this.commentMasterIndex = 10000;
            } else {
              this.$message({
                message: '评论失败',
                type: 'warning'
              });
            }
          }).catch((error) => {
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>
</style>